﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Typing_GUI
{
    public partial class frmAdventure : Form
    {
        #region"BIẾN"
        //string strLesson[];
        List<CLASS.CCapDoNguoiDung> dscapdo = new List<Typing_GUI.CLASS.CCapDoNguoiDung>();
        List<CLASS.CBaiTap> dsbaitap = new List<Typing_GUI.CLASS.CBaiTap>();
        CLASS.CNguoiDung nd = new Typing_GUI.CLASS.CNguoiDung();

        public int userId = 2;//ma cua nguoi dung.
        int startLesson = 0;//bai dau tien.
        int nextWord = 0;//tu dau tien.
        string content = "";//noi dung bai tap.
        string[] nWord = new string[200];//so tu trong 1 bai.
        string[] mang = new string[100];//mang luu cau truc bai tap duoc luu.
        int nLesson = 0;//so luong bai tap cua level.
        int nChar = 5;//so tu trong mot chu.
        int nextchar = 0;//tu ke tiep duoc danh.
        int tg = 0;//thoi gian cua bai tap.(tinh bang giay).
        string tgchuoi = "";//bieu dien thoi gian theo dang chuoi.
        int gioihan = 444;//gioi han cua noi de vien gach.
        bool flag = true;//co cho bien loi chay 1 lan cho 1 chu sai.
        int loi = 0;//dem so loi sai.
        int dem = 0;//dem so lan cho.
        int diem = 0;
        int diemnguoidung = 0;
        float diemthat = 0;
        float diemtungtu = 0;
        bool flagTM2 = true;//co cho phep nhan nut hay khong.
        Point x = new Point(-1, -1);//vi tri mac dinh cua vien gach.
        public int levels = 0;
        int levelnd = 0;
        int time = 0;
        #endregion

        #region"HAM AM THANH"

        void PlaySound(string path)
        {

            // myAudio = new Audio(path);
            // myAudio.Play();

            byte[] result = System.IO.File.ReadAllBytes(path);

            System.IO.MemoryStream ms = new System.IO.MemoryStream(result);

            System.Media.SoundPlayer pl = new System.Media.SoundPlayer(ms);

            pl.Play();

        }
        void AntiFlicker()
        {
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.DoubleBuffer, true);
        }
        void PlayTypeRightSound(string s)
        {
            try
            {
                PlaySound(s);
            }
            catch { }

        }
        void PlayTypeWrongSound()
        {
            try
            {
                PlaySound("Sound/cached_wrong.wav");
            }
            catch { }
        }

        //private void pbHands_Paint(object sender, PaintEventArgs e)
        //{
        //    CLASS.CHands.FindFinger(Paragraph[count], e);
        //}
        //Hàm reset các nút 
        void ResetButtons()
        {
            if (startLesson == 0)
            {
                btnNext.Enabled = true;
                btnPrev.Enabled = false;
            }
            else if (startLesson == nLesson-1)
            {
                btnPrev.Enabled = true;
                btnNext.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
                btnPrev.Enabled = true;
            }
            if (nLesson < 2)
            {
                btnNext.Enabled = false;
                btnPrev.Enabled = false;
            }
        }
        #endregion

        public frmAdventure()
        {
            InitializeComponent();
        }

        private void frmAdventure_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void frmAdventure_Load(object sender, EventArgs e)
        {

            AntiFlicker();
            flagTM2 = false;
            timer1.Stop();
            timer3.Stop();
            timer2.Stop();
            dscapdo = CLASS.CCapDoNguoiDung.GetUserLevels();

            if (levels != -1)
            {
                bool loaded = false;
                CLASS.CBaiTapDuocLuu b = new Typing_GUI.CLASS.CBaiTapDuocLuu();
                b = CLASS.CBaiTapDuocLuu.getSavedAdventureLesson(userId);
                if (b != null)
                {
                    loaded = LoadLessonSave(b);
                }
                nd = CLASS.CNguoiDung.GetUserById(userId);
                levelnd = nd.Capdonguoidung;
                LoadAvatar_Level();
                dsbaitap = CLASS.CBaiTap.GetLessonListByLevel(levels, 2);
                nLesson = dsbaitap.Count;
                nd = CLASS.CNguoiDung.GetUserById(userId);
                diemnguoidung = nd.Tongdiem;

                ////////////////////////////////////////////////////////////////////////
                if (nLesson > 0)
                {

                    content = dsbaitap[startLesson].Noidung;
                    nWord = content.Split(' ');
                    int sotu = 0;
                    for (int i = 0; i < nWord.Length; i++)
                    {
                        sotu += nWord[i].Length;
                    }
                    diemtungtu = (float)dsbaitap[startLesson].Diemtoida / sotu;
                    lblLessonName.Text = dsbaitap[startLesson].Tenbaitap;
                    richBrick.Text = nWord[nextWord];
                    if (CLASS.CDiem.ExistMatch(userId, dsbaitap[startLesson].Mabaitap))
                        lblPassed.Visible = true;
                    else
                        lblPassed.Visible = false;

                    richBrick.Select(0, nextchar);
                    richBrick.SelectionColor = Color.Blue;
                    richBrick.SelectionAlignment = HorizontalAlignment.Center;
                    pbWrong.Visible = false;
                    rtxtDescription.Text = dsbaitap[startLesson].Mota;
                    tg = dsbaitap[0].Thoigian * 60;
                    if (loaded)
                    {
                        //Noi dung luu se la:0tu,1ki tu,2bai,3loi,4gioihan,5x,6y,7diemthat.
                        loi = int.Parse(mang[3]);
                        gioihan = int.Parse(mang[4]);
                        richBrick.Location = new Point(int.Parse(mang[5]), int.Parse(mang[6]));
                        tg = b.Thoigianconlai;
                        lblScore.Text = b.Sodiemdaco.ToString();
                        diemthat = float.Parse(mang[7]);
                        lblErrors.Text = loi.ToString();
                        int gioihan_tam = 444;
                        for (int i = 0; i < (444 - gioihan) / 38; i++)
                        {
                            PictureBox p = new PictureBox();
                            p.Name = Guid.NewGuid().ToString();
                            p.Size = new Size(242, 38);
                            p.ImageLocation = "images/tuongGach21.jpg";
                            p.Location = new Point(-1, gioihan_tam - 38);
                            pnlColumn2.Controls.Add(p);
                            gioihan_tam = gioihan_tam - 38;
                        }

                    }
                    tgchuoi = countTime();
                    lblTime.Text = tgchuoi;
                    nextWord++;
                    startLesson++;
                    btnNext.Enabled = true;
                    btnPrev.Enabled = false;
                    if (startLesson >= nLesson)
                    {
                        btnNext.Enabled = false;
                        btnPrev.Enabled = true;
                    }
                    timer2.Stop();
                    timer3.Start();
                    timer1.Start();
                    flagTM2 = true;
                    //ResetButtons();

                }
                else
                {
                    MessageBox.Show("Do not find exersices.");
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("Do not find levels.");
                this.Close();
            }

        }
        string countTime()
        {
            int mi = tg / 60;
            int se = tg % 60;
            string chuoi = mi.ToString() + ":" + se.ToString();
            return chuoi;
        }
        void loadLessonInLevel()
        {
            clearPannel2();
            flagTM2 = true;
            rtxtDescription.Text = dsbaitap[startLesson].Mota;
            content = dsbaitap[startLesson].Noidung;
            nWord = content.Split(' ');
            richBrick.Text = nWord[0];
            richBrick.Location = x;
            richBrick.SelectAll();
            richBrick.SelectionColor = Color.White;
            richBrick.SelectionAlignment = HorizontalAlignment.Center;
            lblLessonName.Text = dsbaitap[startLesson].Tenbaitap;
            pbWrong.Visible = false;
            pbHands.Invalidate();
            nextWord++;
            int sotu = 0;
            for (int i = 0; i < nWord.Length; i++)
            {
                sotu += nWord[i].Length;
            }
            diemtungtu = (float)dsbaitap[startLesson].Diemtoida / sotu;
            //MessageBox.Show(diemtungtu.ToString(), sotu.ToString());
            if (CLASS.CDiem.ExistMatch(userId, dsbaitap[startLesson].Mabaitap))
                lblPassed.Visible = true;
            else
                lblPassed.Visible = false;
            tg = dsbaitap[startLesson].Thoigian * 60;
            tgchuoi = countTime();
            lblTime.Text = tgchuoi;
            lblScore.Text = "0";
            startLesson++;
            loi = 0; diem = 0; diemthat = 0;
            lblErrors.Text = loi.ToString();
            timer3.Start();
            timer1.Start();
        }
        bool flagExit = false;
        void LoadLesson()
        {
            clearPannel2();
           
            time = 0;
            gioihan = 444;
            nextchar = 0;
            nextWord = 0;
            //MessageBox.Show(startLesson.ToString());
            if (startLesson < nLesson)
            {
                loadLessonInLevel();
            }
            else
            {
                int so = 0;

                do
                {
                    levels++;
                    if (levels > 4)
                        break;
                    dsbaitap = CLASS.CBaiTap.GetLessonListByLevel(levels, 2);
                    so = dsbaitap.Count;
                }
                while (so == 0);
                if (levels > 4)
                {
                    MessageBox.Show("You have completed..");
                    flagExit = true;
                    this.Close();
                    return;
                }
                nLesson = so;
                startLesson = 0;
                nextchar = 0;
                nextWord = 0;
                loadLessonInLevel();

            }
        }

        bool LoadLessonSave(CLASS.CBaiTapDuocLuu b)
        {


            DialogResult kq = MessageBox.Show("do you want load seved lesson?", "note", MessageBoxButtons.OKCancel);
            if (kq == DialogResult.OK)
            {

                string chuoi = b.Noidungdalam;

                mang = chuoi.Split(',');
                //Noi dung luu se la:0tu,1ki tu,2bai,3loi,4gioihan,5x,6y,7diemthat,8level.
                startLesson = int.Parse(mang[2]);
                nextchar = int.Parse(mang[1]);
                nextWord = int.Parse(mang[0]);
                levels = int.Parse(mang[8]);
                return true;
            }
            else
            {

                startLesson = 0;
                nextchar = 0;
                nextWord = 0;
                return false;
            }

        }

        void LoadAvatar_Level()
        {
            string un = CLASS.CNguoiDung.SetAvatar_Level(userId, pbAvatar, pbLevel);
            lblUsername.Text = un;
            ToolTip toolTip1 = new ToolTip();
            toolTip1.SetToolTip(pbLevel, pbLevel.Tag.ToString());
        }

        void doitaodo(RichTextBox a)
        {
            if (gioihan <= 0)
            {
                timer1.Stop();
                flagTM2 = false;
                if (MessageBox.Show("lesson is failed! Do you want to replay this lesson", " Message", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    startLesson -= 1;
                }
                else
                {
                    luudiem();
                    tangLevel();
                }
                LoadLesson();
            }

            if (a.Location.Y <= gioihan - 38)
            {

                Point newlocation = new Point();
                newlocation.X = a.Location.X;
                newlocation.Y = a.Location.Y + 1;
                a.Location = newlocation;
            }
            else
            {
                timer1.Stop();

                ///////////////////////////////////////////////////////
                PictureBox p = new PictureBox();
                p.Name = Guid.NewGuid().ToString();
                p.Size = new Size(242, 38);
                p.ImageLocation = "images/tuongGach21.jpg";
                p.Location = new Point(-1, gioihan - 38);
                pnlColumn2.Controls.Add(p);
                PlayTypeRightSound("Sound/cached_stats.wav");

                if (nextWord == nWord.Length)
                {
                    timer1.Stop();
                    flagTM2 = false; 
                    clearPannel2();
                    MessageBox.Show("lesson ended!!!");
                    luudiem();
                    tangLevel();
                   
                    LoadLesson();

                }
                else
                {
                    Point newlocation = new Point();
                    newlocation.X = -1;
                    newlocation.Y = -38;
                    gioihan = gioihan - 38; 
                    a.Location = newlocation;
                    a.Text = nWord[nextWord];
                    nextWord++;
                    nextchar = 0;
                    pbHands.Invalidate();
                    a.SelectAll();
                    a.SelectionColor = Color.White;
                    a.SelectionAlignment = HorizontalAlignment.Center;
                    timer1.Start();
                }
            }

        }//ham xu ly vien gach.

        private void timer1_Tick(object sender, EventArgs e)
        {
            doitaodo(richBrick);
        }

        private void frmAdventure_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (flagTM2)
            {
                flagTM2 = false;
                if (e.KeyChar == richBrick.Text[nextchar])
                {
                    diemthat += diemtungtu;
                    double temp = diemthat + 0.5;
                    diem = (int)temp;
                    lblScore.Text = diem.ToString();

                    pbWrong.Visible = false;
                    PlayTypeRightSound("Sound/cached_type.wav");
                    int n = nextchar + 1;
                    richBrick.Select(0, n);
                    richBrick.SelectionColor = Color.Blue;
                    richBrick.SelectionFont = new Font(richBrick.Font, FontStyle.Regular);
                    richBrick.Select(n, 1);
                    richBrick.SelectionFont = new Font(richBrick.Font, FontStyle.Underline);
                    nextchar++;

                    if (nextchar < richBrick.Text.Length)
                    {

                        pbHands.Invalidate();
                        flag = true;
                        flagTM2 = true;
                    }
                    else
                    {
                        timer1.Stop();

                        flagTM2 = false;

                        int toadoY = richBrick.Location.Y;
                        bpBrick.Location = new Point(-1, toadoY);
                        bpBrick.Visible = true;
                        timer2.Start();
                    }
                }
                else
                {
                    if (nextchar < richBrick.Text.Length)
                    {

                        pbWrong.Visible = true;
                        PlayTypeWrongSound();
                        if (flag == true)
                        {
                            flag = false;
                            loi++;
                            lblErrors.Text = loi.ToString();
                        }
                        flagTM2 = true;
                    }


                }
            }
        }

        private void frmAdventure_KeyUp(object sender, KeyEventArgs e)
        {
            if (flag == true)
            {

            }

        }

        private void btnBackToMenu_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void pbHands_Click(object sender, EventArgs e)
        {

        }

        private void pbHands_Paint(object sender, PaintEventArgs e)
        {
            if (nextchar < richBrick.Text.Length)
                CLASS.CHands.FindFinger(richBrick.Text[nextchar], e);
        }

        void tangLevel()
        {
            nd = CLASS.CNguoiDung.GetUserById(userId);
            diemnguoidung = nd.Tongdiem;

            int leveltemp = 1;
            for (int i = 0; i < dscapdo.Count; i++)
            {
                if (diemnguoidung > dscapdo[i].DiemChuan)
                    leveltemp = dscapdo[i].MaCapDo + 1;
            }
            //MessageBox.Show(leveltemp.ToString());
            CLASS.CNguoiDung.UpdateTongDiem(userId, diemnguoidung);
            if (levelnd < leveltemp)
            {
                CLASS.CNguoiDung.UpdateLevel(userId, leveltemp);
                frmLevelUp lu = new frmLevelUp();
                levels = leveltemp;
                lu.ShowDialog();
                LoadAvatar_Level();
            }

        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            
            dem++;
            if (dem == 3)
            {
                PlayTypeRightSound("Sound/BreakEgg.wav");
                bpBrick.Visible = false;
                //pnlColumn2.Controls.RemoveByKey("temp");
                if (nextWord == nWord.Length)
                {
                    nextchar = nextchar - 1;
                    flagTM2 = false;

                    timer3.Stop();
                    timer1.Stop();
                    /////////////////////////////////////////////////////////////////
                    frmResultOfLesson rs = new frmResultOfLesson();
                    rs.error = loi;
                    rs.score = diem;
                    rs.userID = userId;
                    rs.lessonName = dsbaitap[startLesson - 1].Tenbaitap;

                    rs.time = time;


                    rs.speed = (int)(((float)nWord.Length / (time))*60 );
                    rs.type = 2;
                    rs.ShowDialog();
                    /////////////////////////////////////////////////////////////////////
                    luudiem();
                    tangLevel();
                    LoadLesson();
                }
                else
                {
                    richBrick.Text = nWord[nextWord];
                    richBrick.Location = new Point(-1, -36);
                    richBrick.SelectAll();
                    richBrick.SelectionAlignment = HorizontalAlignment.Center;
                    richBrick.SelectionColor = Color.White;
                    nextWord++;
                    nextchar = 0;
                    timer1.Start();
                    pbHands.Invalidate(); flag = true; flagTM2 = true;
                }
                timer2.Stop();
                dem = 0;
               
            }
        }

        void clearPannel2()
        {
           
            //while (pnlColumn2.Controls.Count > 1)
            //{
            //    foreach (Control ctrl in pnlColumn2.Controls)
            //    {
            //        if (ctrl.GetType() != typeof(PictureBox))
            //            pnlColumn2.Controls.Remove(ctrl);
            //        else if (ctrl.GetType() == typeof(PictureBox) && ctrl.Name != "bpBrick")
            //            pnlColumn2.Controls.Remove(ctrl);
            //    }
            //}
            for (int i = pnlColumn2.Controls.Count - 1; i > 0; i--)
            {
                if (pnlColumn2.Controls[i].Name != "bpBrick")
                    pnlColumn2.Controls.Remove(pnlColumn2.Controls[i]);
            }
                bpBrick.Visible = false;
            pnlColumn2.Controls.Add(richBrick);
            
       
           

        }

        bool luudiem()
        {
            CLASS.CDiem d = new Typing_GUI.CLASS.CDiem();
            d.Mabaitap = dsbaitap[startLesson - 1].Mabaitap;
            d.Manguoidung = userId;
            d.Sodiem = diem;
            d.Soloisai = loi;
            d.Thoigian = dsbaitap[startLesson - 1].Thoigian;
            d.Tocdo = ((int)(((float)nWord.Length / (time)) * 60)).ToString();
            d.deleteMatch();
            bool kq = d.createMatch();
            return kq;
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            time += 1;
            if (tg == 0)
            {
                timer3.Stop();
                timer2.Stop();
                timer1.Stop();
                flagTM2 = false;
                luudiem();
                tangLevel();
                LoadLesson();
            }
            else
            {
                tg--;
                tgchuoi = countTime();
                lblTime.Text = tgchuoi;
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            button1.Focus();
            if (startLesson >= nLesson)
            {
                btnNext.Enabled = false;
            }
            else
            {
                btnPrev.Enabled = true;
                clearPannel2();
                loadLessonInLevel();
                if (startLesson == nLesson)
                    btnNext.Enabled = false;
            }

        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            button1.Focus();
            startLesson -= 2;
            if (startLesson == 0)
            {
                btnPrev.Enabled = false; btnNext.Enabled = true;
                //startLesson += 2;

            }

            loadLessonInLevel();

            if (startLesson == nLesson)
                btnNext.Enabled = false;


        }

        void save()
        {
            timer1.Stop();
            timer3.Stop();
            flagTM2 = false;
            CLASS.CBaiTapDuocLuu b = new Typing_GUI.CLASS.CBaiTapDuocLuu();
            b.Mabaitap = dsbaitap[startLesson - 1].Mabaitap;
            b.Manguoidung = userId;
            b.Sodiemdaco = diem;
            b.Thoigianconlai = tg;
            nextWord--;
            //nextchar--;
            startLesson--;
            //Noi dung luu se la:tu,ki tu,bai,loi,gioihan,x,y,diemthat,level.
            string chuoi = nextWord.ToString() + "," + nextchar.ToString() + "," + startLesson.ToString();
            chuoi += "," + loi.ToString() + "," + gioihan.ToString() + "," + richBrick.Location.X.ToString();
            chuoi += "," + richBrick.Location.Y.ToString() + "," + diemthat.ToString() + "," + levels.ToString(); ;
            b.Noidungdalam = chuoi;
            CLASS.CBaiTapDuocLuu temp = new Typing_GUI.CLASS.CBaiTapDuocLuu();
            temp = CLASS.CBaiTapDuocLuu.getSavedAdventureLesson(userId);
            if (temp != null)
                CLASS.CBaiTapDuocLuu.deleteSavedlesson(temp.Mabaitap, temp.Manguoidung);
            b.createSavelesson();
               
        }

        private void frmAdventure_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flagExit == false)
            {
                if (nLesson > 0)
                {
                    timer1.Stop();
                    timer3.Stop();
                    flagTM2 = false;
                    DialogResult kq = MessageBox.Show("Do you want to save this lesson?", "Notice", MessageBoxButtons.YesNoCancel);

                    if (kq == DialogResult.Yes)
                        save();
                    else if (kq == DialogResult.Cancel)
                    {
                        //MessageBox.Show(flagExit.ToString());


                        e.Cancel = true;
                        timer1.Start();
                        timer3.Start();
                        flagTM2 = true;
                    }
                }

            }



        }

        private void richBrick_Enter(object sender, EventArgs e)
        {
            button1.Focus();
        }
    }
}
